package script.learn
{
	import eventUtil.EventCenter;
	
	import laya.components.Script;
	import laya.events.Event;
	import laya.ui.UIComponent;
	import laya.ui.View;
	
	import model.ConstantModel;
	import model.lesson.ChineseBookPage;
	import model.lesson.EnglishBookPage;
	
	import ui.learn.BookPagePanelUI;
	
	public class BookPageController extends Script
	{
		private var uiSkin:BookPagePanelUI;
		private var param:Object;
		
		private var curpage:int = 0;
		private var pageview:View;
		
		private var downposX:Number;
		private var mouseDwon:Boolean=false;

		private var threshHold:Number = 200;
		public function BookPageController()
		{
			super();
		}
		
		override public function onStart():void
		{
			uiSkin = this.owner as BookPagePanelUI;
			
			if(param.subject == ConstantModel.SUBJECT_ENGLISH)
			{
				curpage = param.page;
				var ui:View = EnglishBookPage.getPageUI(param.level,param.page);
				if(ui != null)
				{
					pageview = new ui;
					uiSkin.pageContent.addChild(pageview);
					
				}
			}
			else if(param.subject == ConstantModel.SUBJECT_CHINESE)
			{
				curpage = param.page;
				var ui:View = ChineseBookPage.getPageUI(param.level,param.page);
				if(ui != null)
				{
					pageview = new ui;
					uiSkin.pageContent.addChild(pageview);
					
				}
			}
			uiSkin.on(Event.MOUSE_DOWN,this,onStartMove);
			uiSkin.on(Event.MOUSE_UP,this,onStopMove);
			uiSkin.on(Event.MOUSE_OUT,this,onStopMove);

			uiSkin.on(Event.MOUSE_MOVE,this,onMovePage);

			EventCenter.instance.on(EventCenter.SHOW_TRANSLATE_TEXT,this,showTranslate);

			
			
		}
		private function onMovePage(e:Event):void
		{
			if(mouseDwon)
			{
				var offset:Number = e.stageX - downposX;
				if(pageview)
					pageview.x = offset;
			}
		}
		private function onStartMove(e:Event):void
		{
			mouseDwon = true;
			downposX = e.stageX;
		}
		
		private function onStopMove():void
		{
			mouseDwon = false;
			if(pageview)
			{
				if(pageview.x < -threshHold)
				{
					changePage(1);
				}
				else if(pageview.x > threshHold)
				{
					changePage(-1);
				}
				else
				{
					pageview.x = 0;
				}
			}
		}
		private function changePage(dir:int):void
		{
			
			var ui:View = EnglishBookPage.getPageUI(param.level,curpage+dir);
			if(ui != null)
			{
				while(uiSkin.pageContent.numChildren > 0)
					uiSkin.pageContent.removeChildAt(0);
				curpage = curpage+dir;
				pageview = new ui;
				uiSkin.pageContent.addChild(pageview);
				
			}
			pageview.x = 0;
		}
		
		private function showTranslate(txt:String):void{
			
			uiSkin.tanslateLbl.text = txt;
		}
		
		public override function onDestroy():void
		{
			EventCenter.instance.off(EventCenter.SHOW_TRANSLATE_TEXT,this,showTranslate);

		}
	}
}